<template>
  <div>
    <a-modal
      v-model:visible="visible"
      title="退款"
      :confirm-loading="confirmLoading"
      :closable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-row>
        <a-col :sm="24">
          <a-descriptions>
            <a-descriptions-item label="支付订单号">
              <a-tag color="purple">
                {{ data.detailData.payOrderId }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="24">
          <a-descriptions>
            <a-descriptions-item label="支付金额">
              <a-tag color="green">
                {{ data.detailData.amount/100 }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
        <a-col :sm="24">
          <a-descriptions>
            <a-descriptions-item label="可退金额">
              <a-tag color="pink">
                {{ nowRefundAmount }}
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-col>
      </a-row>

      <a-form ref="refundInfo" :rules="rules" :model="data.refund">
        <a-form-item label="退款金额" name="refundAmount">
          <a-input-number v-model:value="data.refund.refundAmount" :precision="2" style="width:100%" />
        </a-form-item>

        <a-form-item label="退款原因" name="refundReason">
          <a-input v-model:value="data.refund.refundReason" type="textarea" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="tsx" >
import { API_URL_PAY_ORDER_LIST, req, $payOrderRefund } from '@/api/manage'
import { ref, reactive, getCurrentInstance, defineProps, defineExpose, computed } from 'vue'
import router from '@/router'

// 定义函数
const props = defineProps({
  callbackFunc: { type: Function, default: () => () => ({}) }
})

// 导入全局函数
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

// refundInfo组件
const refundInfo = ref()


let recordId = ''
let visible= ref(false)
let confirmLoading= ref(false)

let data : any = reactive({
  refundErrorModal: null,  // 退款错误信息的modal对象
  detailData: {} as any,
   refund: {
         refundReason: '', // 退款原因
         refundAmount: '' // 退款金额
      } as any,
})

const rules = {
  refundReason: [{ min: 0, max: 256, required: true, trigger: 'blur', message: '请输入退款原因，最长不超过256个字符' }],
  refundAmount: [{ required: true, message: '请输入金额', trigger: 'blur',type:'number' },
  {
      validator: (rule, value) => {
          if (value < 0.01 || value >  nowRefundAmount.value) {
            return Promise.reject('退款金额不能小于0.01并且不能大于可退金额')
          }else{
            return Promise.resolve()
          }
       
      }
  }
  ]
}


  const nowRefundAmount = computed( () => {
      return ( data.detailData.amount -  data.detailData.refundAmount) / 100
    }
  )

    function show (recordIdParam) {

      if (  refundInfo.value !== undefined) {
          refundInfo.value.resetFields()
        }
       recordId = recordIdParam
       visible.value = true
       data.refund = {}
      req.getById(API_URL_PAY_ORDER_LIST, recordId).then(res => {
         data.detailData = res
      })
    }
    function handleOk (e) {

        refundInfo.value.validate().then( (valid) => {

        confirmLoading.value = true
        // 退款接口
        $payOrderRefund( recordId,  data.refund.refundAmount,   data.refund.refundReason).then(res => {

            visible.value = false // 关闭弹窗
            confirmLoading.value = false // 取消按钮转圈

          if (res.state === 0 || res.state === 3) { // 订单生成 || 失败
            data.refundErrorModal = $infoBox.modalError('退款失败', buildModalText(res))
          } else if (res.state === 1) { // 退款中
            data.refundErrorModal = $infoBox.modalWarning('退款中', buildModalText(res))
            props.callbackFunc()
          } else if (res.state === 2) { // 退款成功
            $infoBox.message.success('退款成功')
            props.callbackFunc()
          } else {
            data.refundErrorModal = $infoBox.modalWarning('退款状态未知', buildModalText(res))
          }
        }).catch(() => {
          confirmLoading.value = false // 取消按钮转圈
        })
      })
    }
    function handleCancel (e) {
       visible.value = false
    }

    // 跳转到退款列表函数
    function toRefundList () {

      data.refundErrorModal.destroy()
      router.push({
        path: '/refund',
      })
    }

    function buildModalText (res) {
      return <div>
        { res.errCode?  <div>错误码：{res.errCode} </div> : '' }
         { res.errMsg?  <div>错误信息：{res.errMsg} </div> : '' }
        <div>请到<a onClick={ toRefundList }>退款列表</a>中查看详细信息</div>
      </div>
    }

defineExpose({ show })

</script>

<style scoped lang="less">

</style>
